package com.ulic.customerManApplication.util.mail;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.ulic.customerManApplication.util.config.ConfigInfo;

/**
 * 发送邮件Util
 * 
 * @author zyt
 * 
 */
public class SendMail {

	String to = "";// 收件人
	String from = "";// 发件人
	String[] copies = null;// 抄送人
	String host = "";// smtp主机
	String username = "";
	String password = "";
	String filename = "";// 附件文件名
	String subject = "";// 邮件主题
	String content = "";// 邮件正文
	Vector file = new Vector();// 附件文件集合
    String mailSignature = "";
	public SendMail(String from, String password) {
		ConfigInfo configinfo = new ConfigInfo();
		this.from = from;
		this.host = configinfo.getPropertiesValue("parameter", "host");
		this.username = from;
		this.password = password;

	}

	/**
	 *<br>
	 * 方法说明：默认构造器 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public SendMail() {
		this.host = "172.22.1.7";
	}

	/**
	 *<br>
	 * 方法说明：构造器，提供直接的参数传入 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public SendMail(String to, String from, String smtpServer, String username,
			String password, String subject, String content) {
		this.to = to;
		this.from = from;
		this.host = smtpServer;
		this.username = username;
		this.password = password;
		this.subject = subject;
		this.content = content;
	}

	/**
	 *<br>
	 * 方法说明：设置邮件服务器地址 <br>
	 * 输入参数：String host 邮件服务器地址名称 <br>
	 * 返回类型：
	 */
	public void setHost(String host) {
		this.host = host;
	}

	/**
	 *<br>
	 * 方法说明：设置登录服务器校验密码 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public void setPassWord(String pwd) {
		this.password = pwd;
	}

	/**
	 *<br>
	 * 方法说明：设置登录服务器校验用户 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public void setUserName(String usn) {
		this.username = usn;
	}

	/**
	 *<br>
	 * 方法说明：设置邮件发送目的邮箱 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public void setTo(String to) {
		this.to = to;
	}

	/**
	 *<br>
	 * 方法说明：设置邮件发送源邮箱 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public void setFrom(String from) {
		this.from = from;
	}

	/**
	 *<br>
	 * 方法说明：设置邮件主题 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public void setSubject(String subject) {
		this.subject = subject;
	}

	/**
	 *<br>
	 * 方法说明：设置邮件内容 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public void setContent(String content) {
		this.content = content;
	}

	/**
	 *<br>
	 * 方法说明：把主题转换为中文 <br>
	 * 输入参数：String strText <br>
	 * 返回类型：
	 */
	public String transferChinese(String strText) {
		try {
			// strText = MimeUtility.encodeText(new String(strText.getBytes(),
			// "GB2312"), "GB2312", "B");
			strText = MimeUtility.encodeText(strText, "GB2312", "B");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strText;
	}

	/**
	 *<br>
	 * 方法说明：往附件组合中添加附件 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public void attachfile(String fname) {
		file.addElement(fname);
	}

	/**
	 *<br>
	 * 方法说明：发送邮件 <br>
	 * 输入参数： <br>
	 * 返回类型：boolean 成功为true，反之为false
	 */
	public boolean sendMail() throws Exception {
		try {
			Properties props = new Properties();
			props.setProperty("mail.smtp.host", ConfigInfo
					.getPropertiesValue("mail.server.smtp"));
			props.setProperty("mail.smtp.auth", "true");
			Session session = Session.getInstance(props);

			Message message = new MimeMessage(session);
			// 设置高优先级
			message.addHeader("X-priority", String.valueOf(1));
			message.isMimeType("");
			// 设置发送人
			InternetAddress mailFrom = null;
			mailFrom = new InternetAddress(ConfigInfo
					.getPropertiesValue("mail.addr"), "合众人寿公益平台");
			message.setFrom(mailFrom);
			// 设置接收人
			InternetAddress[] mailTo = new InternetAddress[1];
			mailTo[0] = new InternetAddress(to);
			message.setRecipients(Message.RecipientType.TO, mailTo);
            
			// 设置抄送人
			InternetAddress[] mailCc = new InternetAddress[1];
			if (copies != null && copies.length != 0) {
				mailCc = new InternetAddress[copies.length];
				int index = 0;
				for (String copy : copies) {
					try {
						mailCc[index++] = new InternetAddress(copy);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				message.setRecipients(Message.RecipientType.CC, mailCc);
			}
			// 设置主题
			message.setSubject(subject);
			// 设置回复邮件地址
			Address[] mailReply = new InternetAddress[1];
			mailReply[0] = new InternetAddress(ConfigInfo
					.getPropertiesValue("mail.addr"));
			message.setReplyTo(mailReply);

			// 设置正文
			Multipart multipart = new MimeMultipart();
			MimeBodyPart mimeBodyPart = new MimeBodyPart();
			mimeBodyPart.setContent(content+mailSignature,"text/html;charset=utf-8"); 
			//mimeBodyPart.setText(content+mailSignature,"text/html;charset=utf-8");
			multipart.addBodyPart(mimeBodyPart);
			
			// 添加附件
			Enumeration efile = file.elements();
			while (efile.hasMoreElements()) {

				filename = efile.nextElement().toString();
				String[] strfile = filename.split(",");
				MimeBodyPart mbpFile = new MimeBodyPart();
				FileDataSource fds = new FileDataSource(strfile[0]);
				mbpFile.setDataHandler(new DataHandler(fds));
				mbpFile.setFileName(getChineseString(strfile[1]));
				
				multipart.addBodyPart(mbpFile);

			}
			

			message.setContent(multipart);
			// 设置发送日期
			message.setSentDate(new Date());
			// message.saveChanges();
	       // message.setContent(content+mailSignature,"text/html;charset=utf-8");
		//	message.setDataHandler(new   DataHandler("您好："+content.toString(), "text/html;charset=utf-8")); 
			
			Transport transport = session.getTransport("smtp");
			transport.connect(
					ConfigInfo.getPropertiesValue("mail.server.smtp"), Integer
							.parseInt(ConfigInfo
									.getPropertiesValue("mail.server.port")),
					ConfigInfo.getPropertiesValue("mail.username"), ConfigInfo
							.getPropertiesValue("mail.password"));
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		} catch (UnsupportedEncodingException uee) {
			uee.printStackTrace();
			return false;
		} catch (AddressException ae) {
			ae.printStackTrace();
			return false;
		} catch (MessagingException me) {
			me.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 *<br>
	 * 方法说明：带参数的邮件发送 <br>
	 * 输入参数： <br>
	 * 返回类型：
	 */
	public boolean sendMails(String to, String[] copies, String title,
			String content,String mailSignature) throws Exception {

		this.to = to;
		this.subject = title;
		this.content = content;
		this.copies = copies;
		this.mailSignature = mailSignature;
		return sendMail();
	}

	public boolean sendMails(String to, String title, String content)
			throws Exception {

		this.to = to;
		this.subject = title;
		this.content = content;
		return sendMail();
	}

	public boolean sendMails(String to, String title, String content,
			String mailSignature) throws Exception {

		this.to = to;
		this.subject = title;
		this.content = content;
		this.mailSignature = mailSignature;
		return sendMail();
	}

	/**
	 *<br>
	 * 方法说明：带参数的邮件群发 <br>
	 * 输入参数： <br>
	 * 返回类型：成功发送的邮件个数 n
	 */
	public int sendMails(List tos, String copies, String title, String content)
			throws Exception {
		int n = 0;
		for (int i = 0; i < tos.size(); i++) {
			String to = (String) tos.get(i);
			if (to != null && to.length() != 0) {
				if (sendMails(to, copies, title, content)) {
					n++;
				}
			}
		}
		return n;
	}

	/**
	 * 群发邮件
	 * 
	 * @param email
	 * @param title
	 * @param content
	 * @return
	 */
	public List<String> sendMails(String[] email, String[] copies, String title,
			String content,String mailSignature) throws Exception {
		List<String> successTos = new ArrayList<String>();  
		for (int i = 0; i < email.length; i++) {
			String to = email[i];
			if (to != null && to.length() != 0) {
				if (sendMails(to, copies, title, content,mailSignature)) {
					successTos.add(to);
				}
			}
		}
		return successTos;
	}

	public int sendMails(String[] email, String title, String content)
			throws Exception {
		int n = 0;
		for (int i = 0; i < email.length; i++) {
			String to = email[i];
			if (to != null && to.length() != 0) {
				if (sendMails(to, title, content)) {
					n++;
				}
			}
		}
		return n;
	}

	public static String getChineseString(String str) {
		String tempStr = "";
		if (str != null && !str.equals("")) {
			try {
				tempStr = new String(str.getBytes(), "ISO-8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return tempStr;
	}

	public void deleteAttachFiles() {
		file.removeAllElements();//
	}
}
